package net.slenderloris.touchclient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.LinkedBlockingQueue;

import android.util.Log;

public class NetworkThread {

	public static final String TAG = NetworkThread.class.getCanonicalName();
	private Thread mThread;
	private OutputStream mOutputStream;
	private LinkedBlockingQueue<byte[]> mQueue = new LinkedBlockingQueue<byte[]>(1024);

	private class NetworkThreadRunnable implements Runnable {
		
		public void run() {
			synchronized (NetworkThread.this) {
				try {
					Log.d(TAG, "Creating socket");
					createSocket();
				} catch (IOException e) {
					e.printStackTrace();
					return;
				}
			}
			
			boolean running = true;
			while(running) {
				try {
					byte[] bytes = mQueue.take();
					if(bytes.length == 0) {
						Log.d(TAG,"Closing stream");
						mOutputStream.close();
						running = false;
					}
					else {
						Log.d(TAG,"writing " + bytes.length);
						mOutputStream.write(bytes);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					running = false;
				} catch (IOException e) {
					e.printStackTrace();
					running = false;
				}
			}
			
		};
		
	}
	
	public NetworkThread() {
		mThread = new Thread(new NetworkThreadRunnable());
		//mThread.setPriority(Thread.MAX_PRIORITY);
		mThread.start();
	}

	private void createSocket() throws IOException {
		InetAddress addr = InetAddress.getByName("192.168.0.2");
		Log.d(TAG, "InetAddress = " + addr);
		Socket s = new Socket(addr, 57392);
		Log.d(TAG, "Got socket");
		mOutputStream = s.getOutputStream();
	}
	
	public void write(byte[] bytes) {
		if(mQueue.remainingCapacity()>0) {
			mQueue.add(bytes);
		}
	}
	
	public void close() {
		mQueue.add(new byte[]{});
	}
	
}
